
import requests
import time
from lxml import etree
from bs4 import BeautifulSoup
import base64
from PIL import Image


def get_session():
    url = 'https://www.ems.com.cn/pc/login/qrcode/login'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Host': 'www.ems.com.cn',
        'Origin': 'https://www.ems.com.cn',
        'Referer': "https://www.ems.com.cn/pc/main/new",
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'X-Requested-With': 'XMLHttpRequest'
    }
    data = {"qr": "1"}
    res = requests.post(url, headers=headers, data=data)
    print(res.headers)
    session = res.headers['Set-Cookie'].replace(' path=/pc/', '')
    print(session)
    return session


def get_code(session):
    t = int(time.time()*1000)
    url = 'https://www.ems.com.cn/pc/common/sms?d={}'.format(t)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
        'Cookie': session
    }
    res = requests.get(url, headers=headers)
    with open('sms_code.png', 'wb') as f:
        f.write(res.content)


def checkCode(session, code):
    url = 'https://www.ems.com.cn/pc/login/loginBeforeCheckVerifyCode'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
        'Accept': '*/*',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': session
    }
    data = {"bfCode": code}
    res = requests.post(url, headers=headers, data=data)
    result = res.json()
    token = result['token']
    return token


def sendCode(session, token):
    url = 'https://www.ems.com.cn/pc/login/smsLognd'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
        'Accept': '*/*',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': session
    }
    data = {
        'mobile': "18718896370",
        'vToken': token
    }
    res = requests.post(url, headers=headers, data=data)
    print(res.text)


def login(session, code):
    print(session)
    url = 'https://www.ems.com.cn/pc/login/byPhone/login'
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Content-Length': '21',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': session,
        'Host': 'www.ems.com.cn',
        'Origin': 'https://www.ems.com.cn',
        'Pragma': 'no-cache',
        'Referer': 'https://www.ems.com.cn/pc/main/new',
        'sec-ch-ua': '" Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"',
        'sec-ch-ua-mobile': '?0',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71',
        'X-Requested-With': 'XMLHttpRequest',
    }
    data = {
        'smsVerify': code,
        'ph': '1'
    }
    res = requests.post(url, headers=headers, data=data)
    print(res.text)


def getData(f,i):
    url = 'https://www.ems.com.cn/pc/orderlist/recv/findByPage'
    headers = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Content-Length': '41',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'SESSION=8f52ab80-1e83-46eb-a0d0-2e692283a4dc; ecun=8ea7062847090a8ebf71406d370f6d62',
        'Host': 'www.ems.com.cn',
        'Origin': 'https://www.ems.com.cn',
        'Pragma': 'no-cache',
        'Referer': 'https://www.ems.com.cn/pc/main/new',
        'sec-ch-ua': '" Not;A Brand";v="99", "Microsoft Edge";v="91", "Chromium";v="91"',
        'sec-ch-ua-mobile': '?0',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71',
        'X-Requested-With': 'XMLHttpRequest'
    }
    data = {
        'querytype': '1',
        'querystr': '',
        'pageNo': str(i),
        'pageSize': '20'
    }
    res = requests.post(url, headers=headers, data=data)
    parser = etree.HTML(res.text)
    data1 = parser.xpath('//*[@class="all"]')
    data2 = parser.xpath('//*[@class="date"]')
    data3 = parser.xpath('//*[@class="position-info"]')
    data4 = parser.xpath('//*[@class="zj"]')
    for i in range(len(data1)):
        dict1 = {}
        dict2 = {}
        dict1['Number'] = data1[i].xpath('./span/span')[0].text
        dict1['createTime'] = data2[i].xpath('./text()')[0]
        dict1['sendcity'] = data3[i].xpath('./div[1]/div')[0].text
        dict1['sendname'] =  data3[i].xpath('./div[1]/span')[0].text
        dict1['status'] = data3[i].xpath('./div[2]/div[2]')[0].text
        dict1['reccity'] = data3[i].xpath('./div[4]/div[1]')[0].text
        dict1['recname'] = data3[i].xpath('./div[4]/span')[0].text
        list1 = []
        dict2['orderStatus'] = data4[i].xpath('./div[2]/div[1]/div[1]')[0].text
        try:
            dict2['orderTime'] = data4[i].xpath('./div[2]/div[1]/div[2]')[0].text
        except:
            dict2['orderTime'] = ''
        dict2['orderinfo'] = data4[i].xpath('./div[2]/div[2]')[0].text
        list1.append(dict2)
        dict1['orderInfo'] = list1
        print(dict1)
        f.write(str(dict1)+'\n')

def get_yzm():
    url = 'https://www.ems.com.cn/ems-web/cutPic/getPic'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71',
    }
    res = requests.post(url,headers=headers)
    print(res.text)

def get_slide():
    url = 'https://www.ems.com.cn/ems-web/cutPic/getPic'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
    }
    res = requests.post(url,headers=headers)
    result = res.json()
    capcode = result['value']['capcode']
    slidingImage = result['value']['slidingImage']
    backImage = result['value']['backImage']
    data = base64.b64decode(slidingImage)
    with open('aaa.png','wb') as f:
        f.write(data)
    back = base64.b64decode(backImage)
    with open('aa.png','wb') as f:
        f.write(back)
    return capcode

def check(capcode,x):
    url = "https://www.ems.com.cn/ems-web/trackTestQuery/getLogisticsTestFlag"
    payload = "{\"value\":{\"customerIP\":\"113.111.212.59\",\"phoneNum\":\"\",\"waybillNoList\":[\"9883529157484\"],\"xpos\":%s,\"capcode\":\"%s\"}}"%(x,capcode)
    headers = {
        'Content-Type': "application/json",
        'Cookie': "jdpt.session.id=96b011b211914164a98ca83c2936aca0",
        'Connection': "keep-alive",
        'User-Agent': "Mozilla/5.0 (Linux; Android 7.1.2; TAS-AN00 Build/TAS-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36 MMWEBID/3766 MicroMessenger/8.0.3.1880(0x28000334) Process/appbrand0 WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android",
        'Referer': "https://www.ems.com.cn/",
        'Cache-Control': "no-cache",
        # 'Postman-Token': "be0d4820-b5a4-47ae-b5b9-102c1f2676a2"
        }
    response = requests.request("POST", url, data=payload, headers=headers)
    print(response.text)

def change_size(png_path, height, width,out_path):
    png = Image.open(png_path)
    png = png.resize((height, width),Image.ANTIALIAS)
    png.save(out_path)

def get_search(capcode,x):
    url = 'https://www.ems.com.cn/ems-web/cutPic/checkcapcode'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
        'Cookie': 'jdpt.session.id=96b011b211914164a98ca83c2936aca0',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json;charset=UTF-8'
    }
    data = "{\"value\":[{\"xpos\":%s,\"capcode\":\"%s\",\"mailStatus\":\"a\",\"orderNum\":[\"9883529157484\"],\"orderType\":\"1\",\"noRulesNum\":[],\"appleFlag\":null}],\"list\":[\"9883529157484\"]}"%(str(x),capcode)
    res = requests.post(url,headers=headers,data=data)
    print(res.text)


# if __name__ == "__main__":
    # session = get_session()
    # get_code(session)
    # code = input("输入验证码")
    # token = checkCode(session, code)
    # sendCode(session, token)
    # sms_code = input("输入短信验证码")
    # login(session, sms_code)
    # f = open('sms_data.txt','a+',encoding='utf-8')
    # for i in range(1,1861):
    #     print('-----------------'+str(i)+'-----------------------------')
    #     getData(f,i)
    #     time.sleep(1.5)
    # f.close()
    # ================================滑块搜索+++++++++++++++++++++++++++++++++++++
    # capcode = get_slide()
    # print(capcode)
    # change_size('E:/nodeProject/aa.png', 350, 200, 'E:/nodeProject/python/aa.png')
    # change_size('E:/nodeProject/aaa.png', 350, 200, 'E:/nodeProject/python/aaa.png')
    # x = input('请输入距离:')
    # check(capcode,x)
    # get_search(capcode,x)
